package com.babel.util.exception;

import com.babel.util.enums.ResultCodeEnum;
import com.babel.util.result.WsResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/***
 *  Created by chenhui on 2017/6/12.
 */
@ControllerAdvice
public class ExceptionHandle {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 统一处理异常防止异常暴露给调用者
     * 将异常日志形式记录下来
     * @param e 异常
     * @return json
     */
    @ExceptionHandler(value = {NotFoundException.class})
    public WsResult handlerServerError(NotFoundException e) {
        logger.warn("请求资源不存在{}", e);
        return new WsResult().error(ResultCodeEnum.CODE_404,e.getMessage());
    }

    @ExceptionHandler(value = {ServerException.class})
    public WsResult handlerServerError(ServerException e) {
        logger.error("服务器异常{}", e);
        return new WsResult().error(ResultCodeEnum.CODE_500,e.getMessage());
    }

    @ExceptionHandler(value = {ParamsException.class})
    public WsResult handlerServerError(ParamsException e){
        logger.warn("参数异常{}", e);
        return new WsResult().error(ResultCodeEnum.CODE_400,e.getMessage());
    }
    @ExceptionHandler(value = {RestException.class})
    public WsResult handlerServerError(RestException e){
        logger.warn("参数异常{}", e);
        return new WsResult().error(ResultCodeEnum.CODE_501,e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public WsResult handle(Exception e){
        logger.error("系统异常{}", e);
        return new WsResult().error(ResultCodeEnum.CODE_500,e.getMessage());
    }

}
